package com.ruoyi.wxmini.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.wxmini.bo.WxUserInfo;
import com.ruoyi.wxmini.config.WxMaProperties;
import com.ruoyi.wxmini.domain.MiniUserInfo;
import com.ruoyi.wxmini.service.IMiniUserInfoService;
import com.ruoyi.wxmini.service.IWxMiniJwtService;
import com.ruoyi.wxmini.util.WXCore;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 微信小程序登录接口
 *
 * @author weijiayu
 * @date 2025/4/25 22:15
 */
@RestController
@AllArgsConstructor
@Slf4j
@RequestMapping("/wxmini")
public class WxLoginController {

    private final WxMaService wxMaService;

    @Resource
    private IMiniUserInfoService userInfoService;
    @Resource
    private IWxMiniJwtService jwtService;





    /**
     * 登陆接口
     */
    @GetMapping("/login")
    public AjaxResult login(String appid, String code, String avatarUrl, String nickName  ) {
        if (StringUtils.isEmpty(code)) {
            return AjaxResult.error("empty jscode");
        }

//        if (!wxMaService.switchover(appid)) {
//            return AjaxResult.error(String.format("can not find appid=[%s] config", appid));
//        }

        WxUserInfo wxUserInfo = new WxUserInfo();
        try {
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
            // 同步微信侧用户信息：如果已注册，返回用户信息；如果未注册，自动注册并保存用户信息
            String openId = session.getOpenid();
            MiniUserInfo miniUserInfo = userInfoService.selectUserInfoByOpenId(openId);
            if (miniUserInfo == null) {
                miniUserInfo = new MiniUserInfo();
                miniUserInfo.setUserId(UUID.randomUUID().toString());
                miniUserInfo.setAvatarUrl(avatarUrl);
                miniUserInfo.setUserName(nickName);
                miniUserInfo.setOpenId(openId);
                miniUserInfo.setUnionId(session.getUnionid());
                userInfoService.insertUserInfo(miniUserInfo);
            }
            // 只返回必要信息给前端
            wxUserInfo.wapper(session, miniUserInfo);
            // 生成令牌，用于自定义业务接口鉴权
            wxUserInfo.setApiToken(jwtService.createToken(miniUserInfo.getUserId()));
            return AjaxResult.success(wxUserInfo);
        } catch (WxErrorException e) {
            log.error(e.getMessage(), e);
            return AjaxResult.error();
        } finally {
            WxMaConfigHolder.remove();
        }
    }


    @Resource
    WxMaProperties wxMaProperties;
    /**
     * 登陆接口
     */
    @GetMapping("login/getPhoneByCode")
    public AjaxResult getPhoneByCode(String code, String encryptedData, String iv  ) {
        if (StringUtils.isEmpty(code)) {
            return AjaxResult.error("empty jscode");
        }

        WxUserInfo wxUserInfo = new WxUserInfo();
        try {
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
            String sessionKey = session.getSessionKey();

            String appid = wxMaProperties.getConfigs().get(0).getAppid();
            //解密获取结果
            String result = WXCore.decrypt(appid, encryptedData, sessionKey, iv);
            JSONObject jsonObject = JSONObject.parseObject(result);
            //防止空指针异常
            String phone = "";
            if(jsonObject!=null) {
                //获取的该手机号并不一定为非空，所以后面需要判断phone是否为null或者""
                phone = jsonObject.getString("phoneNumber");
            }

            // 同步微信侧用户信息：如果已注册，返回用户信息；如果未注册，自动注册并保存用户信息
            String openId = session.getOpenid();
            MiniUserInfo miniUserInfo = userInfoService.selectUserInfoByOpenId(openId);
            if (miniUserInfo == null) {
                miniUserInfo = new MiniUserInfo();
                miniUserInfo.setUserId(UUID.randomUUID().toString());
                miniUserInfo.setOpenId(openId);
                miniUserInfo.setUnionId(session.getUnionid());
                miniUserInfo.setPhone(phone);
                userInfoService.insertUserInfo(miniUserInfo);
            }
            // 只返回必要信息给前端
            wxUserInfo.wapper(session, miniUserInfo);
            // 生成令牌，用于自定义业务接口鉴权
            wxUserInfo.setApiToken(jwtService.createToken(miniUserInfo.getUserId()));
            return AjaxResult.success(wxUserInfo);
        } catch (WxErrorException e) {
            log.error(e.getMessage(), e);
            return AjaxResult.error();
        } finally {
            WxMaConfigHolder.remove();
        }
    }
}
